﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DuplicateMP3Finder
{
    class MP3Comparer
    {
        public MP3Comparer()
        { }
        
        public List<TagLib.File> findDuplicates(List<TagLib.File> files)
        {
            List<TagLib.File> duplicateFiles = new List<TagLib.File>();
            Dictionary<TagLib.File, string> checkFiles = new Dictionary<TagLib.File, string>();
            foreach (TagLib.File f in files)
            {
                checkFiles.Add(f, f.Tag.Title);
            }
            var sortedFiles = (from entry in checkFiles orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
            
            foreach (TagLib.File f in files)
            {
                checkFiles.Remove(f);

                if(f.Tag.Title != null && checkFiles.ContainsValue(f.Tag.Title))
                {

                    var tmp = sortedFiles.Where(val => val.Value == f.Tag.Title);
                    TagLib.File s1 = null;
                    foreach (var file in tmp)
                    {
                        if (checkFiles.ContainsKey(file.Key))
                        {
                            checkFiles.Remove(file.Key);
                            if (s1 == null)
                            {
                                s1 = file.Key;
                            }
                            else if(s1.Tag.Performers[0].ToString() == file.Key.Tag.Performers[0].ToString())
                            {
                                if(!duplicateFiles.Contains(s1))
                                    duplicateFiles.Add(s1);
                                duplicateFiles.Add(file.Key);
                            }
                        }
                        
                    }
                }
            }
            
            return duplicateFiles;
        }
    }
}
